package org.herui.campus.service.properties;


import lombok.Data;
import org.herui.campus.properties.PropertyValueInfo;
import org.shan.spring.cache.CacheChannel;
import org.shan.spring.cache.CacheObject;

import java.util.List;
import java.util.Map;

/**
 * Created by amanda.shan on 2021/2/19.
 */
@Data
public abstract class BaseProperties {
    protected CacheChannel cacheChannel;
    protected String paramnameSpace = "paramnameSpace";

    public abstract Map<String, List<PropertyValueInfo>> getMap();

    public abstract String getTitle();

    public void init() {
        Map<String, List<PropertyValueInfo>> map = getMap();
        for (String region : map.keySet()) {
            List<PropertyValueInfo> valueInfos = map.get(region);
            for (int i = 0; i < valueInfos.size(); i++) {
                PropertyValueInfo valueInfo = valueInfos.get(i);
                CacheObject cacheObject = cacheChannel.get(region, valueInfo.getKey());
                PropertyValueInfo cacheObjectObject = cacheObject.getObject(PropertyValueInfo.class);
                if (cacheObjectObject != null) {
                    valueInfo.setValue(cacheObjectObject.getValue());
                    valueInfo.setEdit(cacheObjectObject.isEdit());
                    valueInfo.setName(cacheObjectObject.getName());
                } else {
                    set(region, valueInfo);
                }
            }
        }
    }

    public String wrapParam(String key) {
        return paramnameSpace + ":" + key;
    }

    public PropertyValueInfo get(String region, String key) {

        List<PropertyValueInfo> propertyValueInfos = getMap().get(region);
        for (PropertyValueInfo propertyValueInfo : propertyValueInfos) {
            if (propertyValueInfo.getKey().equals(key)) {
                return propertyValueInfo;
            }
        }
        return null;
    }

    public void set(String region, PropertyValueInfo propertyValueInfo) {
        List<PropertyValueInfo> propertyValueInfos = getMap().get(region);
        for (PropertyValueInfo valueInfo : propertyValueInfos) {
            if (valueInfo.getKey().equals(propertyValueInfo.getKey())) {
                valueInfo.setValue(propertyValueInfo.getValue());
                valueInfo.setEdit(propertyValueInfo.isEdit());
                valueInfo.setName(propertyValueInfo.getName());
            }
        }
        cacheChannel.set(region, propertyValueInfo.getKey(), propertyValueInfo);
    }

}
